import json

from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from booktest.models import BookInfo

# Create your views here.


# 1、自定义Restful API接口，提供以下五个接口：
# 1）获取所有的图书的信息； GET /books/
# 2）新增一本图书的信息； POST /books/
# 3）获取指定的图书的信息（根据ID）；  GET /books/ID/
# 4）修改指定的图书的信息（根据ID）；   PUT books/ID/
# 5）删除指定的图书的信息（根据ID）。   DELETE /books/ID

# /books/
class BookListView(View):
    def get(self,request):
        """
        1）获取所有的图书的信息； GET /books/
        :param request:
        :return:
        """
        # 1.查询全部的图书信息
        books = BookInfo.objects.all()

        # 2.将对象取出并返回所有图书的json数据，其实就是字典形式，状态码200
        book_list = []
        for book in books:
            # 3.将所有的book对象转换成字典添加到列表中
            book_list.append({
                "btitle":book.btitle,
                "bpub_date":book.bpub_date,
                "bread":book.bread,
                "bcomment":book.bcomment,
                "image":book.image.url if book.image else ''
            })
        # 4.返回数据，其实返回的可以是列表，但是需要将safe参数定义成false
        return JsonResponse(book_list,safe=False)

    def post(self,request):
        """
        2）新增一本图书的信息； POST /books/
        需要接收前端的两个参数：btitle / bpub_date
        :param request:
        :return:
        """
        # 1.接收前端发送的两个参数
        req_data = request.body
        # 2.将原始数据转化为字符串
        req_str = req_data.decode()
        # 3.将字符串转化成字典
        req_dict = json.loads(req_str)
        # 4.获取参数
        btitle = req_dict.get('btitle'),
        bpub_date = req_dict.get('bpub_date')

        # TODO: 省略参数校验过程，后面补充

        # 5.创建对象保存数据到数据库
        book = BookInfo.objects.create(
            btitle = btitle,
            bpub_date = bpub_date

        )
        # 6.将对象转化为字典，返回给客户端
        response = {
            "id":book.id,
            "btitle":book.btitle,
            "bpub_date":book.bpub_date,
            "bread":book.bread,
            "bcomment":book.bcomment,
            "image":book.image.url if book.image else ""
        }
        # 7.自定义状态码为201
        return JsonResponse(response,status=201)

# /books/id/
class BookDetailView(View):
    def get(self,request,id):
        """
        3）获取指定的图书的信息（根据ID）；  GET /books/ID/
        :param request:
        :return:
        """
        # 1.获取参数id

        # 2.根据id查询指定的图书信息
        try:
            book = BookInfo.objects.get(id=id)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)

        # 3.返回图书信息给客户端
        book_dict = {
            "btitle":book.btitle,
            "bpub_date":book.bpub_date,
            "bread":book.bread,
            "bcomment":book.bcomment,
            "image":book.image.url if book.image else ""
        }
        return JsonResponse(book_dict,status=200)
    def put(self,request,id):
        """
        4）修改指定的图书的信息（根据ID）；   PUT books/ID/
        :param request:
        :return:
        """
        # 1.根据id查询图书信息
        try:
            book = BookInfo.objects.get(id=id)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)
        # 2.获取要修改的内容
        req_data = request.body
        req_str = req_data.decode()
        req_dict = json.loads(req_str)

        btitle = req_dict.get("btitle")
        bpub_date = req_dict.get("bpub_date")

        # TODO:暂时省略参数校验的过程
        # 3.修改数据库对应的内容
        book.btitle = btitle
        book.bpub_date = bpub_date
        # 将修改的内容保存到数据库
        book.save()
        # 4.返回修改后的图书信息给客户端
        book_dict = {
            "btitle":book.btitle,
            "bpub_date":book.bpub_date,
            "bread":book.bread,
            "bcomment":book.bcomment,
            "image":book.image.url if book.image else ""
        }
        return JsonResponse(book_dict,status=200)

    def delete(self,request,id):
        """
        5）删除指定的图书的信息（根据ID）。   DELETE /books/ID 204
        :param request:
        :return:
        """
        # 1.根据id查询到指定的图书信息
        try:
            book = BookInfo.objects.get(id=id)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)
        # 2.删除指定的图书信息
        book.delete()
        return HttpResponse(status=204)